package com.user_service.service;


import com.user_service.bean.Follow;
import com.user_service.repository.FollowRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FollowService {
    private final FollowRepository followRepository;
    
    public boolean followUser(Long followerId, Long followeeId){
        if(followerId.equals(followeeId)){
            throw new RuntimeException("不能关注自己");
        }
        
        if(followRepository.existsByFollowerIdAndFolloweeId(followerId,followeeId)){
            throw new RuntimeException("已经关注过该用户");
        }
        
        Follow follow=new Follow();
        follow.setFollowerId(followerId);
        follow.setFolloweeId(followeeId);
        followRepository.save(follow);
        return true;
    }
    
    public boolean unFollow(Long followerId,Long followeeId){ 
        if(!followRepository.existsByFollowerIdAndFolloweeId(followerId,followeeId)){
            throw new RuntimeException("未关注该用户");
        }
        
        followRepository.deleteByFollowerIdAndFolloweeId(followerId,followeeId);
        return true;
    }
    
    public List<Long> getFollowerIds(Long userId){
        return followRepository.findByFolloweeId(userId)
                .stream()
                .map(Follow::getFollowerId)
                .collect(Collectors.toList());
    }
    
    public List<Long> getFolloweeIds(Long userId){
        return followRepository.findByFollowerId(userId)
                .stream()
                .map(Follow::getFolloweeId)
                .collect(Collectors.toList());
    }
    
}
